package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import io.minio.*;
import io.minio.errors.MinioException;
import lombok.SneakyThrows;
import org.apache.logging.log4j.util.StringBuilders;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * @Author yaya
 * @Create 2024/7/24 20:15
 * Description:
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties minioConstantProperties;


    @Override
    @SneakyThrows
    public String fileUpload(MultipartFile file) {

        // 检查是否为图片
        BufferedImage read = ImageIO.read(file.getInputStream());
        if (read == null){
            throw new GuiguException(ResultCodeEnum.IMAGE_ERROR);
        }

        // 检查桶是否已经存在
        String bucketName = minioConstantProperties.getBucketName();
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            // 没有就创建一个新的桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

        // 创建上传的文件名
        String snowName = IdUtil.getSnowflakeNextIdStr();
        String extName = FileUtil.extName(file.getOriginalFilename());
        String dateTime = DateTime.now().toDateStr();
        // 当前日期/雪花算法生成随机数/后缀
        String fileName = dateTime + "/" + snowName + "." + extName;
        // 上传文件
        minioClient.putObject(PutObjectArgs.builder()
                .contentType(file.getContentType())
                .stream(file.getInputStream(), file.getSize(), -1)
                .object(fileName)
                .bucket(bucketName)
                .build());

        // 返回能访问的图片路径
        String url = String.join("/",minioConstantProperties.getEndpointUrl(),bucketName,fileName);
        return url;

    }

}

